<?php

namespace App\Supports\Formatter;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;

class ResponseFormatter
{

    /**
     * 格式化模型
     * @param Model|array $model
     * @param $keyMap
     * @return array
     */
    public static function formatterModel($model, $keyMap)
    {
        if ($model === null) {
            return [];
        }
        if ($model instanceof Model) {
            return ArrayFormatter::convertKEY($model, $keyMap);
        } else {
            return ArrayFormatter::convertKEY($model, $keyMap);
        }
    }

    /**
     * 格式化模型数组
     * @param array $models
     * @param $keyMap
     * @return array
     */
    public static function formatterModels($models, $keyMap)
    {
        $data = [];
        foreach ($models as $model) {
            $data[] = self::formatterModel($model, $keyMap);
        }
        return $data;
    }

    public static function formatterObject($array, $keyMap)
    {
        if (is_int(key($array))) {
            foreach ($array as $i => $item) {
                $data[] = self::formatterObject($item, $keyMap);
            }
        } else {
            if ($array instanceof Model) {
                return ArrayFormatter::convertKEY($array, $keyMap);
            } else {
                return ArrayFormatter::convertKEY($array, $keyMap);
            }
        }
    }

    /**
     * 格式化分页器
     * @param LengthAwarePaginator $paginator
     * @param array $keyMap
     * @return array
     */
    public static function formatterPaginator(LengthAwarePaginator $paginator, $keyMap = [])
    {
        return [
            'page' => self::formatterPaginatorPage($paginator),
            'list' => self::formatterPaginatorItems($paginator->items(), $keyMap)
        ];
    }

    protected static function formatterPaginatorPage(LengthAwarePaginator $paginator)
    {
        return [
            'currentPage' => $paginator->currentPage(),
            'totalCount' => $paginator->total(),
            'pageSize' => (int)$paginator->perPage(),//LengthAwarePaginator 的这个属性可能是字符串类型
            'totalPageCount' => (int)ceil($paginator->total() / $paginator->perPage()),
        ];
    }

    protected static function formatterPaginatorItems(array $items, array $keyMap)
    {
        return ArrayFormatter::arrayConvertKEY($items, $keyMap);
    }
}
